嗨嗨!我是Winnie溫尼~
在前一個章節,我們學到了用來將相同性質的資料集合起來的陣列,以及陣列的基礎應用,包含陣列的值會被[]包覆、資料讀取、長度讀取,而今天要介紹的是新增與刪除,根據前後及指定位置的不同有相對應的使用方法唷~!
變數名稱[索引值] = 值
let addFirstExample = [] //空陣列
addFirstExample[0]="first"
addFirstExample[1]="2"
console.log(addFirstExample) //["first",2]
變數名稱.push(值)
let addSecondExample = [0,1,2]
addSecondExample.push("one")
addSecondExample.push("two")
console.log(addSecondExample) //[0,1,2,one,two]
變數名稱.unshift(值)
let addThirdExample = [0,1,2]
addThirdExample.unshift("one")
addThirdExample.unshift("two")
console.log(addThirdExample) //[one,two,0,1,2]
變數名稱.splice = (起始索引值,往後刪除幾筆資料(含起始資料))
let deleteFirstExample = [one,two,0,1,2]
deleteFirstExample(0,1)
console.log(deleteFirstExample) //[two,0,1,2]
deleteFirstExample(1,2)
console.log(deleteFirstExample) //[two,2]
變數名稱.pop()
let deleteSecondExample = [one,two,0,1,2]
deleteSecondExample.pop()
console.log(deleteSecondExample) //[one,two,0,1]
變數名稱.shift()
let deleteThirdExample = [one,two,0,1,2]
deleteThirdExample.shift()
console.log(deleteThirdExample) //[two,0,1,2]
新手上路,如文章有錯誤或需修正之處,懇請大家多多指教!
那麼,我們明天見囉~